<template>
    <div style="display: flex;margin-left: 90px; height:600px;" >
        <div><el-button  @click="handleASClick()" style="margin-left:80px;background-color: #d0dfe5;opacity: 0.9;">发布社团年检</el-button></div>
            <el-dialog v-model="ASVisible" class="custom-dialog">
                <el-form :model="ruleForm" :rules="ASrules" ref="ASform" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="年检主题" prop="AStheme">
                    <el-input v-model="ASform.theme"></el-input>
                    </el-form-item>
                    <el-form-item label="年检年份">
                    <el-select v-model="ASform.year" placeholder="选择年份">
                        <el-option label="2024" value="2024" />
                        <el-option label="2023" value="2023" />
                        <el-option label="2022" value="2022" />
                        <el-option label="2021" value="2021" />
                        <el-option label="2020" value="2020" />
                        <el-option label="2019" value="2019" />
                    </el-select>
                    </el-form-item>
                    <el-form-item label="上传年检表：" >
                    <input
                        type="file"
                        accept=".docx, .pdf, .zip"
                        @change="handleFileChange"
                        />
                    </el-form-item>
        
                    <el-button type="primary" @click="handleReleaseAS()">发布年检</el-button>
                </el-form>
            </el-dialog>
        <div>
            <el-table :data="as_tableData"  max-height="550" style="width:1290px;margin-top: 50px;margin-left: -140px; background-color: #d0dfe5" stripe :border="true"  >
                <el-table-column fixd prop="year" label="年检年份" width="90" > </el-table-column>
                <el-table-column prop="title" label="名称" width="230"> </el-table-column>
                <el-table-column prop="publisher" label="发布人" width="110"> </el-table-column>
                <el-table-column prop="time" label="发布时间" width="180"> </el-table-column>
                <el-table-column prop="file" label="年检文件" width="260">
                    <template #default="{ row }">
                    <div style="display: flex;align-items:center;">
                        <el-icon><Document /></el-icon>
                        <a :href=row.file.FileUrl >{{ row.file.Filename }}</a>
                    </div>
                    </template>    
                </el-table-column>
                <el-table-column prop="ratio" label="提交率" width="80"> </el-table-column>
                <el-table-column  fixed="right"  label="操作" width="200">
                    <template #default="scope">
                        <el-button @click="as_handleClick(scope.$index)" type="text" style="font-size: 14px;">查看未提交社团</el-button>
                        <el-dialog :append-to-body="true"  v-model="ASdetailsDialogVisible" width=1170px :modal="false" :before-close="as_handleClose" style=" height:600px; "> 
                            <p style="margin-top: -30px;font-size: 20px;margin-left: 10px">未参与年检的社团</p>
                            <div style="height:500px"><el-table :data="asclubstableData"  style="width:1160px; background-color: #d0dfe5" stripe :border="true" max-height="580" max-width="1165" >
                                <el-table-column fixed type="index" width="55"></el-table-column>
                                <el-table-column prop="社团名称" label="社团名称" width="130"> </el-table-column>
                                <el-table-column fixd prop="社团负责人" label="社团负责人" width="110" > </el-table-column>
                                <el-table-column fixd prop="社团负责人联系方式" label="社团负责人联系方式" width="170" > </el-table-column>
                                <el-table-column prop="业务指导老师" label="业务指导老师" width="125"> </el-table-column>
                                <el-table-column prop="业务指导老师联系方式" label="业务指导老师联系方式" width="185"> </el-table-column>
                                <el-table-column prop="行政指导老师" label="行政指导老师" width="125"> </el-table-column>
                                <el-table-column prop="行政指导老师联系方式" label="行政指导老师联系方式" width="197"> </el-table-column>
                            </el-table></div>

                            <div style="display: flex; justify-content: center;margin-top: -20px;margin-left: 800px;">
                                <el-button @click="this.ASdetailsDialogVisible = false">取消</el-button>
                                <el-dropdown style="margin-left: 40px" placement="top">
                                    <el-button type="primary"> 一键导出<i class="el-icon-arrow-down"></i>  </el-button>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item @click="exportform('csv',this.asclubstableData)">CSV格式</el-dropdown-item>
                                            <el-dropdown-item @click="exportform('excel',this.asclubstableData)">Excel格式</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </el-dialog>
                        <el-button type="text" @click="ASdeleterecord(scope.$index)" style="font-size: 14px;margin-left: 10px;">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <div style="display: flex;margin-left: 90px; height:600px;margin-top: 50px;" >
        <div><el-button  @click="handleCEClick()"  style="margin-left:80px;background-color: #d0dfe5;opacity: 0.9;">发布社团评优</el-button></div>
        <el-dialog v-model="CEVisible" class="custom-dialog">
            <el-form :model="ruleForm" :rules="CErules" ref="CEform" label-width="100px" class="demo-ruleForm">
                <el-form-item label="评优主题" prop="CEtheme">
                <el-input v-model="CEform.theme"></el-input>
                </el-form-item>
                    <el-form-item label="评优年份">
                    <el-select v-model="CEform.year" placeholder="选择年份">
                        <el-option label="2024" value="2024" />
                        <el-option label="2023" value="2023" />
                        <el-option label="2022" value="2022" />
                        <el-option label="2021" value="2021" />
                        <el-option label="2020" value="2020" />
                        <el-option label="2019" value="2019" />
                    </el-select>
                    </el-form-item>
                    <el-form-item label="上传评优表：" >
                    <input
                        type="file"
                        accept=".docx, .pdf, .zip"
                        @change="CEhandleFileChange"
                        />
                    </el-form-item>
              
                <el-button type="primary" @click="handleReleaseCE()">发布评优</el-button>
            </el-form>
        </el-dialog>

        <el-table :data="ce_tableData"  style="width:1150px;margin-top: 50px;margin-left: -140px;background-color: #d0dfe5" stripe :border="true" max-height="550" >
            <el-table-column fixd prop="ce_year" label="评优年份" width="90" > </el-table-column>
            <el-table-column prop="ce_title" label="名称" width="230"> </el-table-column>
            <el-table-column prop="ce_publisher" label="发布人" width="110"> </el-table-column>
            <el-table-column prop="ce_time" label="发布时间" width="180"> </el-table-column>
            <el-table-column prop="ce_file" label="评优文件" width="260">
                <template #default="{ row }">
                  <div style="display: flex;align-items:center;">
                    <el-icon><Document /></el-icon>
                    <a :href=row.ce_file.FileUrl >{{ row.ce_file.Filename }}</a>
                  </div>
                </template>    
            </el-table-column>
            <el-table-column prop="ce_ratio" label="提交率" width="80"> </el-table-column>
            <el-table-column  fixed="right"  label="操作" width="200">
                <template #default="scope">
                    <el-button @click="cehandleClick(scope.$index)" type="text" style="font-size: 14px;">查看未提交社团</el-button>
                    <el-dialog :append-to-body="true"  v-model="CEdetailsDialogVisible" width=1170px :modal="false" :before-close="as_handleClose" style=" height:600px; "> 
                            <p style="margin-top: -30px;font-size: 20px;margin-left: 10px">未参与评优的社团</p>
                            <div style="height:500px;"><el-table :data="ceclubstableData"  style="width:1160px; background-color: #d0dfe5" stripe :border="true" max-height="500" max-width="1165" >
                                <el-table-column fixed type="index" width="55"></el-table-column>
                                <el-table-column prop="社团名称" label="社团名称" width="130"> </el-table-column>
                                <el-table-column fixd prop="社团负责人" label="社团负责人" width="110" > </el-table-column>
                                <el-table-column fixd prop="社团负责人联系方式" label="社团负责人联系方式" width="170" > </el-table-column>
                                <el-table-column prop="业务指导老师" label="业务指导老师" width="125"> </el-table-column>
                                <el-table-column prop="业务指导老师联系方式" label="业务指导老师联系方式" width="185"> </el-table-column>
                                <el-table-column prop="行政指导老师" label="行政指导老师" width="125"> </el-table-column>
                                <el-table-column prop="行政指导老师联系方式" label="行政指导老师联系方式" width="197"> </el-table-column>
                            </el-table></div>

                            <div style="display: flex; justify-content: center;margin-top: -20px;margin-left: 800px;">
                                <el-button @click="this.CEdetailsDialogVisible = false">取消</el-button>
                                <el-dropdown style="margin-left: 40px" placement="top">
                                    <el-button type="primary"> 一键导出<i class="el-icon-arrow-down"></i>  </el-button>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item @click="exportform('csv',this.ceclubstableData)">CSV格式</el-dropdown-item>
                                            <el-dropdown-item @click="exportform('excel',this.ceclubstableData)">Excel格式</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </el-dialog>

                    <el-button type="text" @click="CEdeleterecord(scope.$index)" style="font-size: 14px;">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';

export default {
    data(){
        return{
            ASVisible:false,
            CEVisible:false,
            as_clubInfo:[],
            ce_clubInfo:[],
            ass:[],
            ces:[],
            ce_ratio:[],
            as_ratio:[],
            as_tableData:[],
            ce_tableData:[],
            asclubstableData:[],
            ceclubstableData:[],
            as_Names:[],
            ce_Names:[],
            ce_files:[],
            as_files:[],
            ASdetailsDialogVisible:false,
            CEdetailsDialogVisible:false,
            ASform:{
                year:'',
                theme:'',
            },
            CEform:{
                year:'',
                theme:'',
            },
        }
    },

    methods:{
        exportform(format,table) {
            const exportData = table;

            if (format === 'csv') {
                const csvContent = this.convertToCSV(exportData);
                const filename = '未提交社团成员名单.csv';
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

                if (navigator.msSaveBlob) {
                    navigator.msSaveBlob(blob, filename);
                } else {
                    const link = document.createElement('a');
                    if (link.download !== undefined) {
                        const url = URL.createObjectURL(blob);
                        link.setAttribute('href', url);
                        link.setAttribute('download', filename);
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }
                }
            } else if (format === 'excel') {
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(exportData);
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
                const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
                const filename = '未提交社团成员名单.xlsx';
                const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });

                if (navigator.msSaveBlob) {
                    navigator.msSaveBlob(blob, filename);
                } else {
                    const link = document.createElement('a');
                    if (link.download !== undefined) {
                        const url = URL.createObjectURL(blob);
                        link.setAttribute('href', url);
                        link.setAttribute('download', filename);
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }

                }
            }
        },

        convertToCSV(data) {
            const csvRows = [];
            const headers = Object.keys(data[0]);
            csvRows.push(headers.join(','));

            for (const row of data) {
                const values = headers.map(header => {
                    let escaped = ('' + row[header]).replace(/"/g, '\\"');
                    return `"${escaped}"`;
                });
                csvRows.push(values.join(','));
            }
            return csvRows.join('\n');
        },

        showac(){
            if (this.ass == null){
                  return
              }
            else{   
                this.as_tableData = this.ass.map((as,idx) => {
                return {
                    year:as.Year,
                    title: as.CPName,
                    publisher: this.as_Names[idx],
                    time: this.getFormatTime(as.PTime),
                    file:  this.as_files[idx],
                    ratio: this.as_ratio[idx],
                };
            })}

            if (this.ces == null){
                  return
              }
            else{   
                this.ce_tableData = this.ces.map((ce,idx) => {
                return {
                    ce_year:ce.Year,
                    ce_title: ce.CEName,
                    ce_publisher: this.ce_Names[idx],
                    ce_time: this.getFormatTime(ce.PTime),
                    ce_file:  this.ce_files[idx],
                    ce_ratio: this.ce_ratio[idx],
                };
            })}
        },

        getFormatTime(time) {
            let date = new Date(time); 
            let year = date.getFullYear();
            let month = (date.getMonth() + 1).toString().padStart(2, '0'); 
            let day = date.getDate().toString().padStart(2, '0');
            let hours = date.getHours().toString().padStart(2, '0');
            let minutes = date.getMinutes().toString().padStart(2, '0');
            let seconds = date.getSeconds().toString().padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },

        getCurrentDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1，并且保证两位数
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');

            const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

            return formattedDateTime;
            },

        as_handleClick(index) {
            this.ASdetailsDialogVisible =true
            if (this.as_clubInfo[index] == null){
                  return
              }
            else{   
                this.asclubstableData = this.as_clubInfo[index].map((c) => {
                return {
                    社团名称:c.Cname,
                    社团负责人: c.LeaderName,
                    社团负责人联系方式: c.LeaderPhone,
                    业务指导老师: c.TeacherName,
                    业务指导老师联系方式:  c.TeacherPhone,
                    行政指导老师: c.AdminTeacher,
                    行政指导老师联系方式: c.AdminTeacherPhone,
                };
            })}
        }, 

        cehandleClick(index){
            this.CEdetailsDialogVisible =true
            if (this.ce_clubInfo[index] == null){
                  return
              }
            else{   
                this.ceclubstableData = this.ce_clubInfo[index].map((c) => {
                return {
                    社团名称:c.Cname,
                    社团负责人: c.LeaderName,
                    社团负责人联系方式: c.LeaderPhone,
                    业务指导老师: c.TeacherName,
                    业务指导老师联系方式:  c.TeacherPhone,
                    行政指导老师: c.AdminTeacher,
                    行政指导老师联系方式: c.AdminTeacherPhone,
                };
            })}
        },

        as_handleClose(done){
            done();
        },

        ASdeleterecord(index){
            const params = new URLSearchParams();
            params.append('index', this.ass[index].CPID);
            
            axios.get('/deletedASRecord', { params })
            .then(response => {
                this.as_clubInfo = response.data.data.as_clubInfo;
                this.ass = response.data.data.ass;
                this.as_ratio = response.data.data.as_ratio;
                this.as_Names = response.data.data.as_Names;
                this.as_files = response.data.data.as_files;
                ElMessage.success("删除成功！")
                this.showac();
            })

            .catch(error => {
                console.error('Error fetching AS_CEInfo:', error);
            });   
        },

        CEdeleterecord(index){
            const params = new URLSearchParams();
            console.log(this.ces)
            console.log(index)
            params.append('index', this.ces[index].CEID);

            axios.get('/deletedCERecord', { params })
            .then(response => {
                this.ce_clubInfo = response.data.data.ce_clubInfo;
                this.ces = response.data.data.ces;
                this.ce_ratio = response.data.data.ce_ratio;
                this.ce_Names = response.data.data.ce_Names;
                this.ce_files = response.data.data.ce_files;
                this.showac();
                ElMessage.success("删除成功！")
            })

            .catch(error => {
                console.error('Error fetching AS_CEInfo:', error);
            });   
        },

        handleReleaseAS(){
            const formData = new FormData();
            this.currentTime = this.getCurrentDateTime();
            formData.append('uid', this.$store.state.userinfo.account)
            formData.append('file', this.selectedASFile); //年检文件
            formData.append('AsName', this.ASform.theme); //年检主题
            formData.append('applyTime', this.currentTime); //提交时间
            formData.append('year', this.ASform.year); //提交时间

            axios.post('api/manager/ReleaseAS', formData)
                .then(response => {
                    ElMessage.success("您已成功发布年检！");
                    this.as_clubInfo = response.data.data.as_clubInfo;
                    this.ass = response.data.data.ass;
                    this.as_ratio = response.data.data.as_ratio;
                    this.as_Names = response.data.data.as_Names;
                    this.as_files = response.data.data.as_files;   
                    this.ASVisible=false;
                    this.showac();
                })
                .catch(error => {
                ElMessage.error("出现错误！无法发布年检！");
                console.error('Error submitting form:', error);
                });
                
    },

        handleFileChange(event) {
            this.selectedASFile = event.target.files[0];
        },
    
        handleASClick(){
            this.ASform.theme = '',
            this.ASform.year = '',
            this.selectedASFile = '',
            this.ASVisible = true;
        },

        handleReleaseCE(){
            const formData = new FormData();
            this.currentTime = this.getCurrentDateTime();
            formData.append('uid', this.$store.state.userinfo.account)
            formData.append('file', this.selectedCEFile); //文件
            formData.append('CeName', this.CEform.theme); //主题
            formData.append('applyTime', this.currentTime); //提交时间
            formData.append('year', this.CEform.year); //提交时间

            axios.post('api/manager/ReleaseCE', formData)
                .then(response => {
                    ElMessage.success("您已成功发布评优！");
                    this.as_clubInfo = response.data.data.as_clubInfo;
                    this.ce_clubInfo = response.data.data.ce_clubInfo;
                    this.ces = response.data.data.ces;
                    this.ass = response.data.data.ass;
                    this.as_ratio = response.data.data.as_ratio;
                    this.as_Names = response.data.data.as_Names;
                    this.as_files = response.data.data.as_files;
                    this.CEVisible=false;
                    this.showac();
                })
                .catch(error => {
                ElMessage.error("出现错误！无法发布评优！");
                console.error('Error submitting form:', error);
                });
                
        },

        CEhandleFileChange(event) {
            this.selectedCEFile = event.target.files[0];
        },
    
        handleCEClick(){
            this.CEform.theme = '',
            this.CEform.year = '',
            this.selectedCEFile = '',
            this.CEVisible = true;
        },


    },

    mounted() {
        axios.get('/getAS_CE')
        .then(response => {
            this.as_clubInfo = response.data.data.as_clubInfo;
            this.ce_clubInfo = response.data.data.ce_clubInfo;
            this.ces = response.data.data.ces;
            this.ass = response.data.data.ass;
            this.ce_ratio = response.data.data.ce_ratio;
            this.as_ratio = response.data.data.as_ratio;
            this.as_Names = response.data.data.as_Names;
            this.ce_Names = response.data.data.ce_Names;
            this.ce_files = response.data.data.ce_files;
            this.as_files = response.data.data.as_files;
            this.showac();
        })
        .catch(error => {
            console.error('Error fetching AS_CEInfo:', error);
        });
    }
}
</script>

<style>
.table-cell {
  max-height:20px; /* 单元格的最大高度 */
  overflow: hidden; /* 溢出的内容隐藏 */
  white-space: nowrap; /* 文本不换行 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}

/* 如果需要多行省略号，可以使用以下CSS */
.ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 显示的行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>